#!/usr/bin/python
# -*- encoding:utf-8 -*-
__author__ = 'Kelvin Pan <ibmmc@live.com>'
__description__ = 'hosts分组排序, 依据组中域名的拟字典序列(RTFC)'
#TODO:keep old label group order
import sys, os,re

def warn(*msg):
	#print msg
	pass

ipv4_regex = re.compile('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')

def getHostFile():
	'''
	get `hosts` file location in current OS
		Usage : `hosts_file = getHostFile()`
				`hosts = open(hosts_file)`
	'''
	if sys.platform == 'win32': #TODO:OS partition may not be C:\ , 
		return r'C:\Windows\System32\drivers\etc\hosts'
	elif sys.platform  == 'unix':
		return r'/etc/hosts'
	else:
		print 'Unknown OS!WTF!'#TODO:...

def isLabelLine(line):
	'''
	Given a line in `hosts`,RTFC
		Usage : `isLabelLine('204.223.20.1	www.foo.com #Blala')`
	''' #TODO : Consider ipv6 address
	return line.startswith('#') and len(ipv4_regex.split(line)) == 1

def getHostItem(host_domain):
	'''
	Given a line in `hosts`,turn the domain mapping to a object
		Usage : `host = getHostItem('204.223.20.1	www.foo.com #Blala')`
				`host == {
					'ip' : '204.223.20.1', 
					'domain' : 'www.foo.com', 
					'comment' : '#Blala'
					'index' : 'com.foo.www'
				}`
	'''
	host_domain_split = host_domain.split()
	host_item = {
		'ip'      : host_domain_split[0],
		'domain'  : host_domain_split[1],
		'comment' : ' '.join(host_domain_split[2:]),
		'index'   : '.'.join(reversed(host_domain_split[1].split('.')))
	}
	if 2 != len(host_domain_split):
		warn('WARNING: ', host_domain, '=>', repr(host_item))
	return host_item

def main():
	'''
	RTFC
	'''
	hosts_file = open(getHostFile())
	start = False
	prevBlankLine = False
	currentBlockLabel = 'Default'
	hosts_dict={}
	prefix = ''
	for eachline in hosts_file:
		if not start:
			prefix = prefix + eachline
			if eachline.lower().startswith('#start'):
				start = True
				prevBlankLine = True
			continue

		eachline = eachline.strip().lower()
		
		if prevBlankLine and isLabelLine(eachline):
			currentBlockLabel = eachline
			hosts_dict[currentBlockLabel] = []
			continue

		if not eachline:
			prevBlankLine = True
		else:
			prevBlankLine = False
			
			host_domain = eachline
			host_item = getHostItem(host_domain)
			hosts_dict[currentBlockLabel].append(host_item)

	hosts_file.close()

	print prefix

	for label in hosts_dict:
		print '\n\n'+label
		hosts_dict[label].sort(key = lambda x: x['index'])
		for item in hosts_dict[label]:
			print item['ip'] + '\t' + item['domain']  + '\t' +  item['comment']
	
if __name__ == '__main__':
	main()	
